/*
 * Anagrams
Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.
 */
package com.xinpan.exercise;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Anagrams {
    public ArrayList<String> anagrams(String[] strs) 
    {
        // Start typing your Java solution below
        // DO NOT write main() function
        Map<String, List<String>> sortMap = new HashMap<String, List<String>>();
       	ArrayList<String> resList = new ArrayList<String>();
        
        
        for(String str : strs)
        {
            if(str.length() == 0)
                continue;
            
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String sortStr = new String(chars);
            
            if(sortMap.get(sortStr) == null)
            {
            	List<String> strList = new ArrayList<String>();
            	sortMap.put(sortStr, strList);
            }
            sortMap.get(sortStr).add(str);
        }
        
        for(String sortStr : sortMap.keySet())
        {
        	if(sortMap.get(sortStr).size() > 1)
        		resList.addAll(sortMap.get(sortStr));
        }
        
        return resList;
    }
    
    
    public static void main(String[] args)
    {
    	String[] strs = {"asc", "csa"};
    	
    	Anagrams ana = new Anagrams();
    	ana.anagrams(strs);
    }
}
